<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书管理</title>
    <!--引入vue-->
    <script src="../../js/vue.js"></script>
    <!--引入Element-->
    <script src="../../js/index.js"></script>
    <link rel="stylesheet" href="../../css/index.css">
    <!--引入axios-->
    <script src="../../js/axios.min.js"></script>
    <script src="../../js/request.js"></script>

    <style>
        .flex-container {
            display: flex; /* 使用Flexbox布局 */
            align-items: center; /* 垂直居中 */
            justify-content: space-between; /* 均匀分布空间 */
        }

        .input-with-select {
            background-color: #409eff; /* 按钮颜色与el-button一致 */
            width: 300px;
            border-radius: 10px;
        }

        .select-with-button {
            margin-left: 10px; /* 与输入框的间距 */
        }
    </style>
</head>
<body>
<div id="app">

    <div class="flex-container">
        <el-button type="primary" @click="addBook">添加图书</el-button>
        <div>
            <el-input v-model="bookName" placeholder="图书名称" class="input-with-select"></el-input>
            <el-select v-model="classId" filterable placeholder="请选择" class="select-with-button">
                <el-option label="图书类型" value="0"></el-option>
                <el-option v-for="item in options" :key="item.class_id" :label="item.class_name"
                           :value="item.class_id"></el-option>
            </el-select>
            <el-button type="primary" @click="searchByBranchId">搜索</el-button>
            <el-button type="primary" @click="getList">刷新</el-button>
        </div>

    </div>

    <br>
    <div>
        <el-table
                :data="bookTableData"
                height="650"
                border
                style="width: 100%">

            <el-table-column
                    align="center"
                    prop="name"
                    label="图书名称"
                    width="250">
            </el-table-column>

            <el-table-column
                    align="center"
                    prop="author"
                    label="作者">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="publish"
                    label="出版社"
                    width="150">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="ISBN"
                    label="ISBN"
                    width="250">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="language"
                    label="语言">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="类型">
                <template slot-scope="scope">
                    {{ returnClassName(scope.row.class_id) }}
                </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="price"
                    label="价格">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="number"
                    label="剩余数量">
            </el-table-column>

            <el-table-column
                    align="center"
                    fixed="right"
                    label="操作"
                    width="300">
                <template slot-scope="scope">
                    <el-button type="success" @click="bookInfo(scope.row)" size="small">详情</el-button>
                    <el-button type="primary" @click="updateBook(scope.row)" size="small">编辑</el-button>
                    <el-button type="danger" @click="deleteBook(scope.row)" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!--    弹出层-->
    <el-dialog
            :title="title"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose"
    >
        <el-form ref="formRef" :model="bookForm" label-width="80px" :rules="rules">

            <el-form-item label="图书名称" prop="name">
                <el-input v-model="bookForm.name" placeholder="请输入图书名称" :disabled="inputDisabled"></el-input>
            </el-form-item>
            <el-form-item label="作者名称" prop="author">
                <el-input v-model="bookForm.author" placeholder="请输入作者名称" :disabled="inputDisabled"></el-input>
            </el-form-item>
            <el-form-item label="出版社" prop="publish">
                <el-input v-model="bookForm.publish" placeholder="请输入出版社" :disabled="inputDisabled"></el-input>
            </el-form-item>
            <el-form-item label="简介" prop="introduction">
                <el-input v-model="bookForm.introduction" placeholder="请输入图书简介"
                          :disabled="inputDisabled"></el-input>
            </el-form-item>

            <el-form-item label="语言" prop="language">
                <el-select v-model="bookForm.language" placeholder="--语言类型--" :disabled="inputDisabled">
                    <el-option label="中文" value="中文"></el-option>
                    <el-option label="英文" value="英文"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="价格" prop="price">
                <el-input v-model="bookForm.price" placeholder="请输入价格" :disabled="inputDisabled"></el-input>
            </el-form-item>


            <el-form-item label="书籍类型" prop="class_id">
                <el-select v-model="bookForm.class_id" placeholder="--书籍类型--" :disabled="inputDisabled">
                    <el-option v-for="item in options" :key="item.class_id" :label="item.class_name"
                               :value="item.class_id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="数量" prop="number">
                <el-input v-model="bookForm.number" placeholder="请输入数量" :disabled="inputDisabled"></el-input>
            </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
                <el-button @click="bookForm={}" v-if="reset">重置</el-button>
                <el-button type="primary" @click="confirm()">立即提交</el-button>
              </span>
    </el-dialog>


</div>
<script>
    let app = new Vue({
        el: '#app',
        data() {
            return {
                //图书表格数据
                bookTableData: [],
                //图书类型编号
                classId: "0",
                //图书类型名称
                bookName: '',
                //图书类型下拉框数据
                options: [],

                //表单内容
                bookForm: {},
                //弹出层状态
                dialogVisible: false,
                //弹出层标题
                title: '',
                //重置按钮状态
                reset: false,
                //输入框状态
                inputDisabled: false,

                //表单校验规则
                rules: {
                    name: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                    author: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                    publish: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                    introduction: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                    language: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                    price: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                    class_id: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                    number: [
                        {required: true, message: '请填写所有必要字段', trigger: 'blur'}
                    ],
                },
            }
        },
        created() {
            //初始化图书列表
            this.getList()
            //初始化图书类型下拉框
            this.getClassList()
        },
        methods: {
            //获取图书列表
            async getList() {
                console.log("获取图书列表", this.classId, this.bookName)
                await $axios.get("/book?m=getList&name=" + this.bookName + "&classId=" + this.classId).then(res => {
                    console.log(res)
                    if (res.code === 1) {
                        this.bookTableData = res.data
                    }
                }).catch(err => {
                    console.log(err)
                })
            },
            // 获取图书类型下拉框数据
            async getClassList() {
                await $axios.get("/classInfo?m=getList").then(res => {
                    console.log(res)
                    if (res.code === 1) {
                        this.options = res.data
                    }
                })
            },

            // 搜索按钮方法
            searchByBranchId() {
                // 调用图书列表方法
                this.getList()
            },
            //图书添加方法
            addBook() {
                //设置重置按钮的状态
                this.reset = true
                //设置弹出层的状态
                this.dialogVisible = true
                //设置弹出层的标题
                this.title = "添加图书"
            },
            //图书修改方法
            updateBook(row) {
                console.log(row)
                //将当前行的数据赋值给bookForm
                this.bookForm = row
                //设置弹出层的状态
                this.dialogVisible = true
                //设置弹出层的标题
                this.title = "编辑图书"
            },
            //图书删除方法
            async deleteBook(row) {
                console.log(row)
                this.$confirm('是否删除该记录?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 调用图书删除方法
                    $axios.delete("/book?m=delete&id=" + row.book_id).then(res => {
                        if (res.code === 1) {
                            // 提示删除成功
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            // 调用图书列表方法
                            this.getList()
                        } else {
                            // 提示删除失败
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            bookInfo(row) {
                console.log(row)
                //将当前行的数据赋值给bookForm
                this.bookForm = row
                //设置弹出层的状态
                this.dialogVisible = true
                //
                this.inputDisabled = true
                this.title = "图书详情"
            },
            // 弹窗确认按钮方法
            confirm() {
                // 表单验证
                this.$refs.formRef.validate((valid) => {
                    if (valid) {
                        console.log('表单验证通过');

                        // 提交表单或执行其他操作
                        if (this.reset) {
                            // 添加操作
                            $axios.post("/book?m=add", this.bookForm).then(res => {
                                console.log(res)
                                if (res.data.code === 1) {
                                    this.$message({
                                        type: 'success',
                                        message: '添加成功!'
                                    });
                                }
                            }).catch(err => {
                                console.log(err)
                            })
                        } else {
                            this.bookForm.pub_date = this.formatTimestamp(this.bookForm.pub_date)
                            console.log(this.bookForm)
                            // 修改操作
                            $axios.put("/book?m=update", this.bookForm).then(res => {
                                console.log(res)
                                if (res.data.code === 1) {
                                    this.$message({
                                        type: 'success',
                                        message: '修改成功!'
                                    });
                                }
                            }).catch(err => {
                                console.log(err)
                            })
                        }
                        this.getList()
                        //调用关闭前执行的方法
                        this.handleClose()
                    } else {
                        console.log('表单验证失败');
                        // 验证失败，提示用户或处理错误
                        this.$message('请填写所有必要字段')
                    }
                });
            },
            //弹出层关闭前执行的方法
            handleClose() {
                //清空表单数据
                this.bookForm = {}
                //关闭弹出层
                this.dialogVisible = false
                //修改输入框的状态
                this.inputDisabled = false
                //修改重置按钮状态
                this.reset = false
                //重置表单验证结果
                this.$refs.formRef.resetFields();
            },
            //时间戳转换
            formatTimestamp(timestamp) {
                const date = new Date(timestamp); // 使用时间戳创建 Date 对象

                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1，然后补零
                const day = String(date.getDate()).padStart(2, '0'); // 补零
                const hours = String(date.getHours()).padStart(2, '0'); // 补零
                const minutes = String(date.getMinutes()).padStart(2, '0'); // 补零
                const seconds = String(date.getSeconds()).padStart(2, '0'); // 补零
                console.log("时间转换")
                // 构建日期时间字符串
                // return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
                return `${year}-${month}-${day}`;
            },
            //根据传入的类型id返回类型名称
            returnClassName(class_id) {
                console.log(class_id)
                class_name = "暂未分类"
                this.options.forEach(element => {
                    if (element.class_id === class_id) {
                        class_name =  element.class_name
                    }
                })
                return class_name
            }

        },
    })
</script>
</body>
</html>